<template>
	<el-dialog class="abow-dialog" top="10vh" :visible.sync="visible" :title="!appletId ? '新增' : '修改'" :close-on-click-modal="false"
		:close-on-press-escape="false" width="650px">
		<el-dialog class="innerDialog" v-dialogDrag
		      width="650px"
		      :title="innerTitle"
		      :visible.sync="innerImgVisible"
		      append-to-body>
			  <div class="d-flex a-cneter j-center">
				  <el-image :style="{width: '650px',height: '450px'}" :src="clickImg" fit="scale-down"></el-image>
			  </div>
		</el-dialog>
		<el-form class="form" :model="dataForm" :rules="dataRule" ref="dataForm" label-width="120px" size="medium"
			:inline="false" labelSuffix="：">
			<el-form-item prop="name" label="名称">
				<el-input clearable v-model="dataForm.name" placeholder="名称" />
			</el-form-item>
			<el-form-item prop="app_id" label="appId">
				<el-input clearable v-model="dataForm.app_id" placeholder="appId" />
			</el-form-item>
			<el-form-item v-if="!appletId" prop="app_secret" label="密钥">
				<el-input clearable v-model="dataForm.app_secret" placeholder="密钥" />
			</el-form-item>
		
			<el-form-item prop="type" label="类型">
				<el-select clearable :disabled="ischange" v-model="dataForm.type" placeholder="请选择">
					<el-option v-for="item in appletTypeList" :key="item.value" :label="item.label" :value="item.value"></el-option>
				</el-select>
			</el-form-item>
			<el-form-item prop="cover" label="小程序图标">
				<div class="d-flex">
					<img v-if="dataForm.cover" class="d-flex mr-20 pointer" :src="dataForm.cover" @click.stop="lookImg(dataForm.cover,dataForm.name+' 小程序图标')"
						style="width: 80px;border-radius: 5px;">
					<div class="d-flex a-center">
						<el-button style="width: 80px;height: 40px;" v-if="$hasPermission('playlet:sts:uploadPath')"
							@click="uploadBtnFn('coverFileBtn','cover')">上传</el-button>
						<input type="file" ref="coverFileBtn" class="position-absolute top-0 left-0 d-none"
							@change="getFiles($event,'images','coverImg')" />
					</div>
				</div>
			</el-form-item>
			<el-form-item prop="user_default_headimg" label="小程序默认头像">
				<div class="d-flex">
					<img v-if="dataForm.user_default_headimg" class="d-flex mr-20 pointer" :src="dataForm.user_default_headimg" @click.stop="lookImg(dataForm.user_default_headimg,dataForm.name+' 小程序默认头像')"
						style="width: 80px;border-radius: 5px;">
					<div class="d-flex a-center">
						<div class="position-relative">
							<el-button style="width: 80px;height: 40px;" v-if="$hasPermission('playlet:sts:uploadPath')"
								@click="uploadBtnFn('headimgFileBtn','user_default_headimg')">上传</el-button>
							<input type="file" ref="headimgFileBtn" class="position-absolute top-0 left-0 d-none"
								@change="getFiles($event,'images','headImg')" />
						</div>
					</div>
				</div>
			</el-form-item>
			<el-form-item prop="coin_name" label="金币名称">
				<el-input clearable v-model="dataForm.coin_name" placeholder="金币名称" />
			</el-form-item>
			<el-form-item v-if="!appletId" prop="token" label="token">
				<el-input clearable v-model="dataForm.token" placeholder="token" />
			</el-form-item>
			<el-form-item prop="static_base_url" label="静态文件">
				<el-input clearable v-model="dataForm.static_base_url" placeholder="静态文件" />
			</el-form-item>
			<el-form-item prop="status" label="状态">
				<el-select clearable v-model="dataForm.status" placeholder="请选择">
					<el-option v-for="(item,index) in status" :key="index" :label="item.label"
						:value="item.value"></el-option>
				</el-select>
			</el-form-item>
		</el-form>
		<template slot="footer">
			<el-button @click="visible = false">{{ $t('views.public.cancel') }}</el-button>
			<el-button type="primary" @click="dataFormSubmitHandle()">{{ $t('views.public.confirm') }}</el-button>
		</template>
	</el-dialog>
</template>

<script>
	let that;
	import {
		debounce
	} from 'lodash'
	import {
		isURL,
		isString
	} from '@/libs/validate';
	import schema from 'async-validator';
	import uploadTools from "./uploadTools";
	export default {
		mixins: [uploadTools],
		data() {
			return {
				ischange:true,
				appletId: null,
				field: '',
				innerTitle:'',
				innerImgVisible:false,
				clickImg:'',
				status: [{
						value: 0,
						label: '禁用',
					},
					{
						value: 1,
						label: '正常',
					}
				],
				visible: false,
				deptList: [],
				deptListVisible: false,
				fullscreenLoading: false,
				showcoverImgProgress: false,
				showheadImgProgress: false,
				showvideosProgress: false,
				roleList: [],
				roleIdListDefault: [],
				dataForm: {
					name: '', //名称
					app_id: '',
					app_secret: '',
					cover: '',
					user_default_headimg: '',
					coin_name: '',
					token: '',
					static_base_url: '',
					type: null,
					status: 1, //状态
				}
			}
		},
		props:{
			appletTypeList:{
				type:Array
			}
		},
		created() {},
		mounted() {
			that = this;
		},
		computed: {
			dataRule() {
				var validateString = (rule, value, callback) => {
					if (/\S/.test(value)&&!isString(value)) {
						return callback(new Error('格式错误！只能是数字或字母，不能有特殊字符'))
					}
					callback()
				}
				var validateUrl = (rule, value, callback) => {
					if (/\S/.test(value)&&!isURL(value)) {
						return callback(new Error('链接格式错误！'))
					}
					callback()
				}
				return {
					name: [{
						required: true,
						message: '名称不能为空!',
						trigger: ['blur','change']
					}],
					app_id: [{
						required: true,
						message: 'appId不能为空!',
						trigger: ['blur','change']
					},
					{
						required: true,
						validator: validateString,
						trigger: ['blur','change']
					}],
					app_secret: [{
						required: true,
						message: '秘钥不能为空!',
						trigger: ['blur','change']
					},{
						required: true,
						validator: validateString,
						trigger: ['blur','change']
					}],
					cover: [{
						required: true,
						message: '小程序图标不能为空!',
						trigger: ['blur','change']
					}],
					status: [{
						required: true,
						message: '状态不能为空!',
						trigger: ['blur','change']
					}],
					type: [{
						required: true,
						message: '类型不能为空!',
						trigger: ['blur','change']
					}],
					token: [{
						required: false,
						validator: validateString,
						trigger: ['blur','change']
					}],
					static_base_url: [{
						required: false,
						validator: validateUrl,
						trigger: ['blur','change']
					}],
				}
			}
		},
		methods: {
			lookImg(clickImg,title) {
				this.clickImg = clickImg;
				this.innerTitle = title;
				this.innerImgVisible = true;
			},
			async getFiles(event,fileType,progress_field) {
				this.showProgress = false;
				const files = event.target.files;
				console.log(files);
				if (files.length) {
					let file = files[0];
					let checkRes = false;
					//图片
					if (fileType == 'images') {
						//检查文件格式和大小
						checkRes = this.checkPicFile(file, 1);
						this.uploadBefore(file,fileType,progress_field,checkRes);
					} else if (fileType == 'videos') {
						//视频
						checkRes = this.checkVideoFile(file, 500);
						this.uploadBefore(file,fileType,progress_field,checkRes);
					}
				}
				event.target.value = '';
			},
			//获取上传密钥和文件路径再上传
			uploadBefore(file,fileType,progress_field,checkRes){
				if (checkRes) {
					this.$axios.post(`/playlet/sts/uploadPath`, {
						type: fileType,
						suffix:this.getFileName(file.name)
					}).then(stsRes=>{
						console.log(stsRes);
						if (typeof stsRes == 'object' && stsRes != null) {
							this.createOss(stsRes.token);
							this.handleUpload(file,fileType,progress_field,stsRes.file_path + stsRes.file_name);
						}else{
							this.$message({
								message: '上传失败！',
								type: 'error',
								duration: 1500
							})
						}
					})
				}
			},
			handleUpload(file,fileType,progress_field,uploadPath) {
				console.log('handleUploadhandleUpload');
				// 获取文件的后缀名
				// let objName = getFileNameUUID()
				var obj = file.name;
				var index = obj.lastIndexOf(".");
				obj = obj.substring(index, obj.length);
				// 生成的文件名，保留文件后缀名，进行拼接      
				let objName = this.getFileNameUUID() + this.getFileName(file.name);
				// 分片上传文件
				console.log(this.client);
				this.client.multipartUpload(`${uploadPath}`, file,{
					progress: async function(p) {
						that['show'+progress_field+'Progress'] = true;
						that.percentage = Math.floor(p * 100);
					}
				}).then(clientRes => {
					console.log(clientRes, 'res')
					if(typeof clientRes == 'object' && clientRes!=null){
						if(typeof clientRes.res == 'object' && clientRes.res!=null){
							if(Array.isArray(clientRes.res.requestUrls)){
								if(clientRes.res.requestUrls.length){
									let requestUrl = this.removeUrlParams(clientRes.res.requestUrls[0]);
									if(!requestUrl){
										return this.$message({
											message: '上传失败！链接为空',
											type: 'error',
											duration: 1500
										})
									}
									if(fileType == 'images'){
										this.$set(this.dataForm, this.field, requestUrl);
									}else if(fileType == 'videos'){
										let video_cover = requestUrl+"?x-oss-process=video/snapshot,t_1000,f_jpg,w_0,h_0,m_fast,ar_auto";
										console.log(requestUrl);
										this.$set(this.dataForm, this.field, requestUrl);
										console.log(this.dataForm);
										this.videoOptions.video.url = requestUrl;
										this.videoOptions.video.pic = video_cover;
									}
									this.$refs.dataForm.validateField(this.field);
									this['show'+progress_field+'Progress'] = false;
									return this.$message({
										message: '上传成功！',
										type: 'success',
										duration: 1500
									})
								}
							}
						}
					}
					this['show'+progress_field+'Progress'] = false;
					this.$message({
						message: '上传失败！',
						type: 'error',
						duration: 1500
					})
				}).catch(err=>{
					console.log(err);
					this['show'+progress_field+'Progress'] = false;
					this.$message({
						message: '上传失败！',
						type: 'error',
						duration: 1500
					})
				})
			},
			uploadBtnFn(fileBtn, field) {
				this.field = field;
				this.$refs[fileBtn].click();
			},
			init() {
				this.visible = true;
				this.$nextTick(() => {
					this.$refs.dataForm.resetFields();
				})
			},
			update(row) {
				this.visible = true;
				this.$nextTick(() => {
					this.dataForm = Object.assign({}, row)
					this.dataForm.comPassword = row.password
					this.$refs.dataForm.clearValidate()
				})
			},
			
			// 表单提交
			dataFormSubmitHandle: debounce(function() {
				console.log('表单提交');
				this.$refs.dataForm.validate((valid) => {
					console.log(valid + '--+++++-----------')
					if (!valid) {
						return false
					}
					console.log(this.dataForm);
					this.$axios.post(this.appletId ? `/api/playlet/applet/update/${this.appletId}` :
						'/api/playlet/applet/create', this.dataForm).then(res => {
						this.$message({
							message: this.$t('views.public.success'),
							type: 'success',
							duration: 1200,
							onClose: () => {
								this.visible = false;
								this.$emit('refreshDataList');
							}
						})
					}).catch(() => {})
				})
			}, 1000, {
				leading: true,
				trailing: false
			})
		}
	}
</script>

<style lang="scss" scoped>
	.form {
		width: 540px;
	}

	.innerDialog :deep(.el-dialog__header){
		padding: 20px!important;
	}
	.innerDialog :deep(.el-dialog__body){
		padding: 0px!important;
	}
	.innerDialog :deep(.el-dialog__headerbtn){
		font-size: 25px!important;
	}
</style>